<template>
	<view class="wrap">
		<image :src="src" @error="loadError" mode="aspectFill" :style="{width: width,height:height,borderRadius:radius}"></image>
	</view>
</template>

<script>
	import { SysAvatar } from '@/utils/sql/avatar';
	
	export default {
		props: {
			url: {
				type: String,
				default () {
					return ''
				}
			},
			id: {
				type: Number,
				default () {
					return ''
				}
			},
			width: {
				type: String,
				default () {
					return '';
				}
			},
			height: {
				type: String,
				default () {
					return '';
				}
			},
			radius: {
				type: String,
				default () {
					return '';
				}
			}
		},
		data() {
			return {
				src: '' // 图片地址
			}
		},
		created() {
			this.getImageCache();
		},
		methods: {
			// 本地存储图片被删除
			async loadError(err) {
				try {
          // 删除
          // #ifdef APP-PLUS
          await SysAvatar.deleteById(this.id);
          // #endif
          // 再次下载
          this.getImageCache();
        } catch (error) {
          this.src = this.url;
        }
			},
			// 判断本地是否存储图片
			async getImageCache() {
				const that = this;

          // #ifdef APP-PLUS
          // 首先获取本地存储的数据，查询是否有对应文件路径，如果有缓存内容，直接返回
          const result = await SysAvatar.select(this.id);
          if(result.length > 0) {
            // 读取本地地址
            this.src = result[0].img_url;
          }else {
            // 下载保存
            uni.downloadFile({
              url: that.url,
              success: (res) => {
                if (res.statusCode === 200) {
                  // 再进行本地保存
                  uni.saveFile({
                    tempFilePath: res.tempFilePath,
                    success: function(res2) {
                      // 保存成功存储路径
                      SysAvatar.insert({worker_id: that.id, img_url: res2.savedFilePath});
                      that.src =  res2.savedFilePath
                    },
                    fail: function(res2) {
                      console.log('保存失败', res2);
                      that.src = this.url;
                    }
                  })
                } else {
                  console.log('下载临时文件失败')
                  that.src = this.url;
                }
              },
              fail: (err) => {
                console.log('下载失败',err)
                that.src = this.url;
              }
            })
          }
          // #endif

          // #ifdef H5
          this.src = this.url;
          // #endif
        
		
			},
		}
	}
</script>

<style scoped lang="scss">
	.wrap {}
</style>